﻿using System;
using System.Collections.Generic;
using System.Data.Services;
using System.Data.Services.Common;
using System.Linq;
using System.ServiceModel.Web;
using System.Web;
using Microsoft.Samples.DPE.OAuth;
using CivilleDataServiceRole;

namespace CivilleWebRole.Services
{
    public class CivilleDataService : DataService<CivilleEntities>
    {
        // This method is called only once to initialize service-wide policies.
        public static void InitializeService(DataServiceConfiguration config)
        {

            // TODO: set rules to indicate which entity sets and service operations are visible, updatable, etc.
            // Examples:
            // config.SetEntitySetAccessRule("MyEntityset", EntitySetRights.AllRead);
            // config.SetServiceOperationAccessRule("MyServiceOperation", ServiceOperationRights.All);
            //config.DataServiceBehavior.MaxProtocolVersion = DataServiceProtocolVersion.V2;
            config.SetEntitySetAccessRule("Tasks", EntitySetRights.All);
            config.SetEntitySetAccessRule("SuggestedTasks", EntitySetRights.All);
            config.SetEntitySetAccessRule("QRCodes", EntitySetRights.All);
            config.SetEntitySetAccessRule("BusinessTypes", EntitySetRights.All);
            config.SetEntitySetAccessRule("BusinessSubTypes", EntitySetRights.All);
            config.SetEntitySetAccessRule("TaskTypes", EntitySetRights.All);
            config.SetEntitySetAccessRule("Stakeholders", EntitySetRights.All);
            config.SetEntitySetAccessRule("CivilleUsers", EntitySetRights.All);
            config.SetEntitySetAccessRule("CivilleUserToCivilleUsers", EntitySetRights.All);
            config.SetEntitySetAccessRule("Bonus", EntitySetRights.All);
            config.SetEntitySetAccessRule("CivilleUserToBonus", EntitySetRights.All);
            config.SetEntitySetAccessRule("Achievements", EntitySetRights.All);
            config.SetEntitySetAccessRule("CivilleUserToAchievements", EntitySetRights.All);
            config.SetEntitySetAccessRule("Rewards", EntitySetRights.All);
            config.SetEntitySetAccessRule("CivilleUserToRewards", EntitySetRights.All);
            config.SetEntitySetAccessRule("Levels", EntitySetRights.All);
            config.SetEntitySetAccessRule("MobileUsers", EntitySetRights.All);
        }

        private static void ThrowIfNotAuthenticated()
        {
            var identity = HttpContext.Current.User.Identity;
            if (identity == null || !identity.IsAuthenticated)
            {
                OAuthHelper.SendUnauthorizedResponse(new OAuthError { Error = OAuthErrorCodes.UnauthorizedClient }, HttpContext.Current);
            }
        }

        protected override void OnStartProcessingRequest(ProcessRequestArgs args)
        {
            //ThrowIfNotAuthenticated();
            base.OnStartProcessingRequest(args);
        }
    }
}
